package com.cloud.shopping.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cloud.shopping.cart.model.Cart;
import com.cloud.shopping.goods.mapper.AdItemsMapper;
import com.cloud.shopping.goods.model.AdItems;
import com.cloud.shopping.goods.model.Sku;
import com.cloud.shopping.goods.mapper.SkuMapper;
import com.cloud.shopping.goods.service.SkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author John.zhang
 * @since 2020-12-29
 */
@Service
@CacheConfig(cacheNames = "ad-items-skuas")
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {

    @Resource
    private SkuMapper skuMapper;

    @Resource
    private AdItemsMapper adItemsMapper;


    /***
     * 库存递减
     * @param carts carts
     */
    @Override
    public void dCount(List<Cart> carts) {
        for (Cart cart : carts) {
            //库存递减
            int dCount = skuMapper.dCount(cart.getSkuId(), cart.getNum());
            if (dCount <= 0) {
                throw new RuntimeException("库存不足！");
            }
        }
    }

    @Override
    @Cacheable(key = "#id")
    public List<Sku> typeSkuItems(Integer id) {
        //1.查询当前分类下的所有列表信息
        List<AdItems> adItemsList = getAdItemsList(id);

        //2.根据推广列表查询产品列表信息
        List<String> skuIds = adItemsList.stream().map(AdItems::getSkuId).collect(Collectors.toList());
        if (skuIds.size() <= 0) {
            return null;
        }
        return skuMapper.selectBatchIds(skuIds);
    }

    @Override
    @CacheEvict(key = "#id")
    public void delTypeSkuItems(Integer id) {

    }

    @Override
    @CachePut(key = "#id")
    public List<Sku> updateTypeSkuItems(Integer id) {
        //1.查询当前分类下的所有列表信息
        List<AdItems> adItemsList = getAdItemsList(id);
        //2.根据推广列表查询产品列表信息
        List<String> skuIds = adItemsList.stream().map(AdItems::getSkuId).collect(Collectors.toList());
        return skuIds.size() <= 0 ? null : skuMapper.selectBatchIds(skuIds);
    }


    /**
     * 查询当前分类下的所有列表信息
     *
     * @param id id
     * @return List
     */
    private List<AdItems> getAdItemsList(Integer id) {
        //1.查询当前分类下的所有列表信息
        QueryWrapper<AdItems> adItemsQueryWrapper = new QueryWrapper<>();
        adItemsQueryWrapper.eq("type", id);
        List<AdItems> adItems = adItemsMapper.selectList(adItemsQueryWrapper);
        return adItems;
    }
}
